package com.imay.live.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.activity.BaseActivity;
import com.imay.base.util.StringUtil;
import com.imay.base.widget.TitleBar;
import com.imay.live.adapter.IndicatorFragmentAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.fragment.RankingFragment;
import com.imay.live.fragment.dynamics.LinearFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.model.RankingGameModel;
import com.imay.live.model.RankingModel;
import com.imay.live.model.TabIndicatorModel;
import com.imay.live.params.IMParams;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.indicator.IndicatorViewPager;
import com.imay.live.view.indicator.ScrollIndicatorView;
import com.imay.live.view.indicator.slidebar.ColorBar;
import com.imay.live.view.indicator.transition.OnTransitionTextListener;
import com.imay.live.R;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * create by nick
 * 发现排行榜
 */
public class DiscoveryRankingListActivity extends BaseActivity implements ProtoCallBack {

    private ScrollIndicatorView siv_ranking;
    private ViewPager vp_ranking;
    private List mTabModelList;
    private String rankType;
    private int count = 100;
    private int start;
    private String discovetyGainMeiliMonthCommand, discovetyGainMeiliDayCommand, discovetySendDiamondMonthCommand, discovetySendDiamondDayCommand, discovetyLikeMonthCommand, discovetyLikeDayCommand, discovetyGameCommand;
    public static final String[] rankTypeArray = {"gainMeili", "sendDiamond", "like", "game"};
    private String[] rankInTimeArray = {"month", "day"};
    private List<RankingModel> rankingGainMeiliMonthModels, rankingGainMeiliDayModels, rankingSendDiamondMonthModels, rankingSendDiamondDayModels, rankingLikeMonthModels, rankingLikeDayModels;
    private List<List<RankingGameModel>> gameRankingModels;
    private ArrayList<Fragment> fragmentList;
    private FrameLayout mFrameLayout;
    private Fragment gameRankingFragment;


    public static void start(Context context) {
        Intent starter = new Intent(context, DiscoveryRankingListActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_raking_list;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mTabModelList = new ArrayList<>(2);
        rankingGainMeiliMonthModels = new ArrayList<>();
        rankingGainMeiliDayModels = new ArrayList<>();
        rankingSendDiamondMonthModels = new ArrayList<>();
        rankingSendDiamondDayModels = new ArrayList<>();
        rankingLikeMonthModels = new ArrayList<>();
        rankingLikeDayModels = new ArrayList<>();
        gameRankingModels = new ArrayList<>();
        TitleBar titleBar = getTitleBar();
        RadioGroup radioGroup = (RadioGroup) LayoutInflater.from(this).inflate(R.layout.view_discovery_ranking_title, null);
        RadioButton button = (RadioButton) radioGroup.findViewById(R.id.rb_like_game);
        if (IMParams.isShowRankingGame) {
            button.setVisibility(View.VISIBLE);
        } else {
            button.setVisibility(View.GONE);
        }
        titleBar.getMiddleView().addView(radioGroup);


        mTabModelList.add(new TabIndicatorModel(getString(R.string.discovery_ranking_day), false));
        mTabModelList.add(new TabIndicatorModel(getString(R.string.discovery_ranking_month), false));

        vp_ranking = $(R.id.vp_ranking);
        siv_ranking = $(R.id.siv_ranking);
        mFrameLayout = $(R.id.fragment_id);

        getContentView().setBackgroundResource(R.drawable.shape_corner10_white);

        bindFragment();
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            final int finalI = i;
            ((RadioButton) radioGroup.getChildAt(i)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        rankType = rankTypeArray[finalI];
                        loadRankingDisCovery();
                        if (finalI == 0) {
                            MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_star");
                        } else if (finalI == 1) {
                            MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_wealth");
                        } else if (finalI == 2) {
                            MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_popular");
                        } else if (finalI == 3) {
                            MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_game");
                        }
                    }

                }
            });
        }
        ((RadioButton) radioGroup.getChildAt(0)).setChecked(true);


    }


    private void bindFragment() {
        fragmentList = new ArrayList<>(2);
        fragmentList.add(RankingFragment.newInstance(RankingFragment.TYPE_DISCOVERY_RANKING));
        fragmentList.add(RankingFragment.newInstance(RankingFragment.TYPE_DISCOVERY_RANKING));
        vp_ranking.setOffscreenPageLimit(1);
        gameRankingFragment = RankingFragment.newInstance(RankingFragment.TYPE_GAME_RANKING);

        ColorBar colorBar = new ColorBar(this, this.getResources().getColor(R.color.indicator_bar_select), this.getResources().getDimensionPixelOffset(R.dimen.indicator_height));
        siv_ranking.setScrollBar(colorBar);

        siv_ranking.setOnTransitionListener(new OnTransitionTextListener().setColorId(this, R.color.indicator_text_select, R.color.indicator_text_unselect));
        IndicatorViewPager indicatorViewPager = new IndicatorViewPager(siv_ranking, vp_ranking);
        indicatorViewPager.setAdapter(new IndicatorFragmentAdapter(this, getSupportFragmentManager(), fragmentList, mTabModelList) {
        });
        indicatorViewPager.setOnIndicatorPageChangeListener(new IndicatorViewPager.OnIndicatorPageChangeListener() {
            @Override
            public void onIndicatorPageChange(int preItem, int currentItem) {
                for (int i = 0; i < rankTypeArray.length; i++) {
                    if (rankType.equals(rankTypeArray[i])) {
                        if (i == 0) {
                            if (currentItem == 0) {
                                MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_star_month");
                            } else {
                                MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_star_day");
                            }
                        } else if (i == 1) {
                            if (currentItem == 0) {
                                MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_wealth_month");
                            } else {
                                MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_wealth_day");
                            }
                        } else {
                            if (currentItem == 0) {
                                MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_popular_month");
                            } else {
                                MobclickAgent.onEvent(DiscoveryRankingListActivity.this, "lists_popular_day");
                            }
                        }
                    }
                }

            }
        });
    }

    private void loadRankingDisCovery() {
        mFrameLayout.setVisibility(View.GONE);
        if (rankTypeArray[0].equals(rankType)) {
            if (StringUtil.isEmpty(discovetyGainMeiliMonthCommand)) {
                DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), "");
                discovetyGainMeiliMonthCommand = ProtoRequestHelper.task(ProtoHttpFactory.getDiscoverRanking(rankType, rankInTimeArray[0], count, start)).setTag(this.hashCode()).request(this);
                discovetyGainMeiliDayCommand = ProtoRequestHelper.task(ProtoHttpFactory.getDiscoverRanking(rankType, rankInTimeArray[1], count, start)).setTag(this.hashCode()).request(this);
            } else {
                ((RankingFragment) fragmentList.get(0)).setRankingData(rankingGainMeiliDayModels);
                ((RankingFragment) fragmentList.get(1)).setRankingData(rankingGainMeiliMonthModels);
            }
            vp_ranking.setCurrentItem(0);
        } else if (rankTypeArray[1].equals(rankType)) {
            if (StringUtil.isEmpty(discovetySendDiamondMonthCommand)) {
                DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), "");
                discovetySendDiamondMonthCommand = ProtoRequestHelper.task(ProtoHttpFactory.getDiscoverRanking(rankType, rankInTimeArray[0], count, start)).setTag(this.hashCode()).request(this);
                discovetySendDiamondDayCommand = ProtoRequestHelper.task(ProtoHttpFactory.getDiscoverRanking(rankType, rankInTimeArray[1], count, start)).setTag(this.hashCode()).request(this);
            } else {
                ((RankingFragment) fragmentList.get(0)).setRankingData(rankingSendDiamondDayModels);
                ((RankingFragment) fragmentList.get(1)).setRankingData(rankingSendDiamondMonthModels);
            }
            vp_ranking.setCurrentItem(0);
        } else if (rankTypeArray[2].equals(rankType)) {
            if (StringUtil.isEmpty(discovetyLikeMonthCommand)) {
                DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), "");
                discovetyLikeMonthCommand = ProtoRequestHelper.task(ProtoHttpFactory.getDiscoverRanking(rankType, rankInTimeArray[0], count, start)).setTag(this.hashCode()).request(this);
                discovetyLikeDayCommand = ProtoRequestHelper.task(ProtoHttpFactory.getDiscoverRanking(rankType, rankInTimeArray[1], count, start)).setTag(this.hashCode()).request(this);
            } else {
                ((RankingFragment) fragmentList.get(0)).setRankingData(rankingLikeDayModels);
                ((RankingFragment) fragmentList.get(1)).setRankingData(rankingLikeMonthModels);
            }
            vp_ranking.setCurrentItem(0);
        } else if (rankTypeArray[3].equals(rankType)) {
            if (StringUtil.isEmpty(discovetyGameCommand)) {
                DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), "");
                discovetyGameCommand = ProtoRequestHelper.task(ProtoHttpFactory.getGameRanking()).setTag(this.hashCode()).request(this);
            } else {
                ((RankingFragment) gameRankingFragment).setGameRankingData(gameRankingModels);
            }
            addFragment(gameRankingFragment);
        }
    }


    @Override
    public void onRequestSuccess(String command, String data) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        if (command.equals(discovetyGainMeiliMonthCommand)) {
            Result<List<RankingModel>> result = JSON.parseObject(data, new TypeReference<Result<List<RankingModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                rankingGainMeiliMonthModels.addAll(result.data);
                setRankModelTag(rankingGainMeiliMonthModels, rankTypeArray[0]);
                ((RankingFragment) fragmentList.get(1)).setRankingData(rankingGainMeiliMonthModels);
            }
        } else if (command.equals(discovetyGainMeiliDayCommand)) {
            Result<List<RankingModel>> result = JSON.parseObject(data, new TypeReference<Result<List<RankingModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                rankingGainMeiliDayModels.addAll(result.data);
                setRankModelTag(rankingGainMeiliDayModels, rankTypeArray[0]);
                ((RankingFragment) fragmentList.get(0)).setRankingData(rankingGainMeiliDayModels);
            }


        } else if (command.equals(discovetySendDiamondMonthCommand)) {
            Result<List<RankingModel>> result = JSON.parseObject(data, new TypeReference<Result<List<RankingModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                rankingSendDiamondMonthModels.addAll(result.data);
                setRankModelTag(rankingSendDiamondMonthModels, rankTypeArray[1]);
                ((RankingFragment) fragmentList.get(1)).setRankingData(rankingSendDiamondMonthModels);
            }

        } else if (command.equals(discovetySendDiamondDayCommand)) {
            Result<List<RankingModel>> result = JSON.parseObject(data, new TypeReference<Result<List<RankingModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                rankingSendDiamondDayModels.addAll(result.data);
                setRankModelTag(rankingSendDiamondDayModels, rankTypeArray[1]);
                ((RankingFragment) fragmentList.get(0)).setRankingData(rankingSendDiamondDayModels);
            }


        } else if (command.equals(discovetyLikeMonthCommand)) {
            Result<List<RankingModel>> result = JSON.parseObject(data, new TypeReference<Result<List<RankingModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                rankingLikeMonthModels.addAll(result.data);
                setRankModelTag(rankingLikeMonthModels, rankTypeArray[2]);
                ((RankingFragment) fragmentList.get(1)).setRankingData(rankingLikeMonthModels);
            }
        } else if (command.equals(discovetyLikeDayCommand)) {
            Result<List<RankingModel>> result = JSON.parseObject(data, new TypeReference<Result<List<RankingModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                rankingLikeDayModels.addAll(result.data);
                setRankModelTag(rankingLikeDayModels, rankTypeArray[2]);
                ((RankingFragment) fragmentList.get(0)).setRankingData(rankingLikeDayModels);
            }
        } else if (command.equals(discovetyGameCommand)) {
            Result<List<List<RankingGameModel>>> result = JSON.parseObject(data, new TypeReference<Result<List<List<RankingGameModel>>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                gameRankingModels.addAll(result.data);
                ((RankingFragment) gameRankingFragment).setGameRankingData(gameRankingModels);
            }
        }
    }


    @Override
    public void onRequestError(String command, int code, String message) {

        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());

    }

    private void setRankModelTag(List<RankingModel> rankingModelList, String type) {
        if (rankingModelList.size() > 0) {
            rankingModelList.get(0).setRankType(type);
        }
    }

    private void addFragment(Fragment rankingFragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag(RankingFragment.class.toString());
        if (fragment == null) {
            transaction.add(R.id.fragment_id, rankingFragment, RankingFragment.class.toString());
        }
        transaction.show(rankingFragment);
        transaction.commitAllowingStateLoss();
        mFrameLayout.setVisibility(View.VISIBLE);
    }
}
